#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
从PDF文件中提取文本内容
"""

import sys
import io

# 修复Windows控制台中文显示乱码问题
if sys.platform == 'win32':
    import io
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
    sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8', errors='replace')
    try:
        import os
        os.system('chcp 65001 >nul 2>&1')
    except:
        pass

try:
    import fitz  # PyMuPDF
except ImportError:
    print("请先安装PyMuPDF: pip install PyMuPDF")
    sys.exit(1)

def extract_pdf_text(pdf_path):
    """从PDF文件中提取文本"""
    try:
        doc = fitz.open(pdf_path)
        full_text = ""
        
        for page_num, page in enumerate(doc, 1):
            print(f"正在读取第 {page_num} 页...")
            text = page.get_text()
            full_text += f"\n=== 第 {page_num} 页 ===\n"
            full_text += text
        
        doc.close()
        return full_text
    except Exception as e:
        print(f"提取PDF文本时出错: {str(e)}")
        return None

if __name__ == "__main__":
    pdf_path = "智能客服知识语料.pdf"
    
    print("开始提取PDF内容...")
    text = extract_pdf_text(pdf_path)
    
    if text:
        print("\n提取到的文本内容：")
        print("=" * 80)
        print(text[:2000])  # 只显示前2000字符
        print("=" * 80)
        print(f"\n总长度: {len(text)} 字符")
        
        # 保存到文件
        output_file = "pdf_content.txt"
        with open(output_file, 'w', encoding='utf-8') as f:
            f.write(text)
        print(f"\n内容已保存到: {output_file}")
    else:
        print("无法提取PDF内容")

